<template>
  <div>
    <!-- <div>
      <span>用户运动问卷已填写，点击</span>
      <a-button type="link" style="padding-left: 0" @click="getDietQuestion">查看详情</a-button>
    </div> -->
    <a-form
      ref="manaPlanFormRef"
      class="mana-plan-form"
      :label-col="{ style: { width: '80px' } }"
      :disabled="isPushed"
      :model="updatedData"
    >
      <template v-if="updatedData.length">
        <div class="mana-plan-item-info">
          <a-form-item label="当前模板库">
            <div style="display: flex; align-items: center; justify-content: space-between">
              <div style="display: flex; align-content: center">
                <a-space :size="[0, 0]">
                  <span
                    @click="changeTemplate(updatedData[0], '公共模板')"
                    :class="
                      updatedData[0].templateAffiliation == '公共模板'
                        ? 'template-col template-col-active'
                        : 'template-col'
                    "
                    >运动方案模板库</span
                  >
                  <span
                    @click="changeTemplate(updatedData[0], '个人模板')"
                    :class="
                      updatedData[0].templateAffiliation == '个人模板'
                        ? 'template-col template-col-active'
                        : 'template-col'
                    "
                    >个人模板库</span
                  >
                  <span
                    @click="changeTemplate(updatedData[0], 'AI生成')"
                    :class="
                      updatedData[0].templateAffiliation == 'AI生成'
                        ? 'template-col template-col-active'
                        : 'template-col'
                    "
                    >AI生成</span
                  >
                </a-space>
              </div>

              <!-- <a-button type="link" danger @click="removePlanItem(index)"> 删除 </a-button> -->
            </div>
          </a-form-item>
          <div v-for="(item, index) in updatedData" :key="index">
            <div
              class="mana-plan-time"
              @click="item.onShowTask = !item.onShowTask"
              v-if="item.templateAffiliation == 'AI生成' && item.cycleStart"
            >
              <template v-if="item.onShowTask">
                <CaretDownOutlined />
              </template>
              <template v-else>
                <CaretRightOutlined />
              </template>
              <span class="time-label">
                {{ dayjs(item.cycleStart).format('YYYY/MM/DD') }}
                -
                {{ dayjs(item.cycleEnd).format('YYYY/MM/DD') }}
              </span>
              <a-tag
                v-if="item.pushStatus == '待推送'"
                style="color: #f53f3f; background-color: #ffece8; border-color: #f53f3f"
                >待推送</a-tag
              >
              <a-tag
                v-if="item.pushStatus == '已推送'"
                style="color: #00b42a; background-color: #e8ffea; border-color: #00b42a"
                >已推送</a-tag
              >
              <a-tag v-if="item.pushStatus == '未推送'">未推送</a-tag>
            </div>
            <template v-if="item.onShowTask || item.templateAffiliation != 'AI生成'">
              <div :class="['mana-plan-task', item.cycleStart ? 'mana-plan-ai' : '']">
                <div
                  v-if="
                    item.templateAffiliation == 'AI生成' &&
                    (item.pushStatus == '待推送' || !item.pushStatus)
                  "
                  style="display: flex; align-items: center"
                >
                  <template v-if="item.aiStatus == 30">
                    <img class="ai-state-icon" src="@/assets/health/ai-error.png" alt="" />
                  </template>
                  <template v-if="!item.aiStatus || item.aiStatus == 20 || item.aiStatus == 10">
                    <img class="ai-state-icon" src="@/assets/health/ai-normal.png" alt="" />
                  </template>
                  <span>{{ item.aiCodeLabel }}</span>
                  <a-button
                    type="primary"
                    @click="regenerate(item)"
                    style="margin-left: 12px"
                    v-if="!item.aiStatus || item.aiStatus == 30"
                  >
                    {{ transformAISattus(item) }}
                  </a-button>
                  <template v-if="item.aiStatus == 40">
                    <div style="display: flex; align-items: center; margin-left: 12px">
                      <img
                        style="width: 16px; height: 16px"
                        src="@/assets/health/loading.png"
                        alt=""
                      />
                      <a-button type="link" @click="regenerate(item)" style="padding-left: 8px">
                        重新生成
                      </a-button>
                    </div>
                  </template>

                  <a-button
                    type="primary"
                    v-if="item.aiStatus == 40"
                    @click="showAiDetail(item, index)"
                  >
                    查看AI生成方案
                  </a-button>
                </div>
                <!-- 模板选择 -->
                <template v-if="item.templateAffiliation != 'AI生成'">
                  <a-form-item label="选择模板" :rules="[{ required: true, message: '选择模板' }]">
                    <a-select
                      v-model:value="item.templateId"
                      placeholder="请选择模板"
                      :options="item.templateList"
                      @change="templateChange(item, $event, index)"
                      showSearch
                    />

                    <a-button type="link" @click="showIndividual(item)"
                      >保存当前已修改方案到个人模板</a-button
                    >
                  </a-form-item>
                </template>
                <!-- 模板选择 -->
                <a-divider
                  style="margin: 12px 0"
                  v-if="
                    item.pushStatus == '待推送' ||
                    !item.pushStatus ||
                    item.templateAffiliation != 'AI生成'
                  "
                />
                <!-- 内容 -->
                <div>
                  <div>
                    <div class="sprot-form">
                      <a-tabs
                        v-model:activeKey="item.activeKey"
                        @change="(event) => tabsChange(event, item)"
                      >
                        <a-tab-pane
                          v-for="(child, childIndex) in item.content.week"
                          :key="childIndex"
                        >
                          <template #tab>
                            <template v-if="item.templateAffiliation == 'AI生成'">
                              第{{ weekDay[child.day - 1] }}天
                            </template>
                            <template v-else> {{ weekLabel[child.day - 1] }}运动 </template>
                          </template>
                          <a-form-item label="运动类型" required>
                            <a-radio-group
                              @change="changesportType(child, index, $event, childIndex)"
                              :options="sportTypeData"
                              :disabled="getDayDisabled(item)"
                              v-model:value="child.sportType"
                            />
                          </a-form-item>
                          <template v-if="child.sportType != '3'">
                            <a-form-item label="有氧运动" required v-if="child.sportType == '1'">
                              <a-select
                                v-model:value="child.aerobicSport.sportName"
                                showSearch
                                :options="aerobicData"
                                placeholder="请选择运动"
                                :listHeight="200"
                                @change="aerobicChange(child, index, $event)"
                                :disabled="getDayDisabled(item)"
                              />
                              <a-form-item-rest>
                                <a-input-number
                                  v-model:value="child.aerobicSport.total"
                                  style="width: 150px; margin: 0 8px"
                                  step="1"
                                  min="1"
                                  :precision="0"
                                  :formatter="formatter"
                                  :parser="parser"
                                  addon-after="分钟"
                                  :disabled="getDayDisabled(item)"
                                />
                              </a-form-item-rest>
                            </a-form-item>
                            <a-form-item label="抗阻动作" required v-if="child.sportType == '2'">
                              <div class="sport-group">
                                <div
                                  class="sport-name"
                                  v-for="(sport, sportIndex) in child.resistanceSports"
                                  :key="sportIndex"
                                >
                                  <span>
                                    {{ sport.sportName }}，
                                    <span
                                      class="sport-time"
                                      @click="
                                        showSport('resistanceSports', 'edit', index, sportIndex)
                                      "
                                    >
                                      每组
                                      {{ sport.total }}
                                      次
                                    </span>
                                  </span>

                                  <CloseOutlined
                                    class="sport-del-icon"
                                    @click="delSport('resistanceSports', index, sportIndex)"
                                    v-if="!isPushed && !getDayDisabled(item)"
                                  />
                                </div>
                                <div
                                  class="sport-btn"
                                  v-if="!isPushed && !getDayDisabled(item)"
                                  @click="showSport('resistanceSports', 'add', index)"
                                >
                                  新增
                                  <PlusOutlined class="icon-add" />
                                </div>
                              </div>
                            </a-form-item>
                            <a-form-item label="动作组数" required v-if="child.sportType == '2'">
                              <a-input-number
                                v-model:value="child.groupNum"
                                step="1"
                                min="1"
                                :precision="0"
                                addonAfter="组"
                                :formatter="formatter"
                                :parser="parser"
                                :disabled="getDayDisabled(item)"
                              />
                            </a-form-item>
                            <a-form-item label="热身运动" required>
                              <div class="sport-group">
                                <div
                                  class="sport-name"
                                  v-for="(sport, sportIndex) in child.warmupSports"
                                  :key="sportIndex"
                                >
                                  <span>
                                    {{ sport.sportName }}，
                                    <span
                                      class="sport-time"
                                      @click="showSport('warmupSports', 'edit', index, sportIndex)"
                                    >
                                      {{ sport.total }}
                                      次
                                    </span>
                                  </span>

                                  <CloseOutlined
                                    class="sport-del-icon"
                                    @click="delSport('warmupSports', index, sportIndex)"
                                    v-if="!isPushed && !getDayDisabled(item)"
                                  />
                                </div>
                                <div
                                  class="sport-btn"
                                  v-if="!isPushed && !getDayDisabled(item)"
                                  @click="showSport('warmupSports', 'add', index)"
                                >
                                  新增
                                  <PlusOutlined class="icon-add" />
                                </div>
                              </div>
                            </a-form-item>
                            <a-form-item label="拉伸运动" required>
                              <div class="sport-group">
                                <div
                                  class="sport-name"
                                  v-for="(sport, sportIndex) in child.stretchSports"
                                  :key="sportIndex"
                                >
                                  <span>
                                    {{ sport.sportName }}，
                                    <span
                                      class="sport-time"
                                      @click="showSport('stretchSports', 'edit', index, sportIndex)"
                                    >
                                      {{ sport.total }}
                                      s
                                    </span>
                                  </span>

                                  <CloseOutlined
                                    class="sport-del-icon"
                                    @click="delSport('stretchSports', index, sportIndex)"
                                    v-if="!isPushed && !getDayDisabled(item)"
                                  />
                                </div>
                                <div
                                  class="sport-btn"
                                  v-if="!isPushed && !getDayDisabled(item)"
                                  @click="showSport('stretchSports', 'add', index)"
                                >
                                  新增
                                  <PlusOutlined class="icon-add" />
                                </div>
                              </div>
                            </a-form-item>
                          </template>
                        </a-tab-pane>
                      </a-tabs>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </div>
        </div>
      </template>
      <!-- <a-button
        @click="addPlanItem"
        :icon="h(PlusOutlined)"
        type="primary"
        ghost
        v-if="!isPushed && updatedData.length == 0"
        class="add-plan-item"
      >
        添加
      </a-button> -->
    </a-form>

    <!-- 个人模板保存 -->
    <a-modal
      v-model:open="individualOpen"
      title="保存当前方案到个人模板"
      :maskClosable="false"
      :destroyOnClose="true"
    >
      <a-form ref="individualForm" :model="individualFormData" style="margin-top: 14px">
        <div style="margin-bottom: 16px; font-weight: bold">{{ individualName }}</div>
        <a-form-item
          name="templateName"
          :rules="[{ required: true, message: '请输入模板名称', whitespace: true }]"
        >
          <a-auto-complete
            style="width: 100%"
            placeholder="请输入模板名称"
            :options="individualTemplateList"
            v-model:value="individualFormData.templateName"
            :filter-option="filterOption"
            @blur="
              (value) => {
                individualFormData.templateName = individualFormData.templateName.replace(
                  /\s+/g,
                  ''
                )
              }
            "
          />
          <span
            v-if="
              individualTemplateList.findIndex((item) => {
                return item.value === individualFormData.templateName
              }) >= 0
            "
            style="color: red"
            >您当前选择的是已存在的模板，保存将覆盖原有模板内容</span
          >
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button @click="individualOpen = false">取消</a-button>
        <a-button type="primary" @click="saveIndividual">保存</a-button>
      </template>
    </a-modal>

    <a-modal
      width="720px"
      v-model:open="sportOpen"
      :title="!sportFormDisable ? '添加运动' : '修改运动'"
      :maskClosable="false"
      ok-text="确认"
      cancel-text="取消"
    >
      <a-form :label-col="{ style: { width: '100px' } }" :model="sportForm" ref="sportFormRef">
        <a-form-item label="运动方式" required name="sport">
          <a-select
            show-search
            v-model:value="sportForm.sport"
            :options="addSportModalData"
            style="width: 100%"
            placeholder="请选择运动方式"
            :listHeight="200"
            :disabled="sportFormDisable"
            @change="sportModalChange"
            :key="new Date().getTime()"
          />
        </a-form-item>
        <a-form-item :label="sportTimeName" required name="time">
          <a-input-number
            v-model:value="sportForm.time"
            :min="0"
            :step="timeStep"
            :precision="0"
            style="width: 100%"
            @change="sportTimeChange"
          />
          <span style="color: #999">{{ sportTimeName }}需为{{ timeStep }}的倍数</span>
        </a-form-item>
      </a-form>

      <template #footer>
        <a-button
          @click="
            () => {
              ;(sportOpen = false), sportFormRef.clearValidate()
            }
          "
        >
          取消
        </a-button>
        <a-button type="primary" @click="sportConfirm">确认</a-button>
      </template>
    </a-modal>

    <!-- <QuestionAnswer ref="questionAnswerRef" /> -->
    <AiDetail ref="aiDetailRef" @setPlan="setAiPlan" />
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, h, defineEmits, watchEffect } from 'vue'
import {
  PlusOutlined,
  CloseOutlined,
  RedoOutlined,
  CaretDownOutlined,
  CaretRightOutlined
} from '@ant-design/icons-vue'
import store from '@/store'
import {
  getAiCycleTask,
  getTemplateDetailList,
  TemplateAddOrUpdate
} from '@/api/healthManaWorkbench/index'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
// import QuestionAnswer from './questionAnswer.vue'
import { getAiRecommendScheme, getAiRecommendSchemeDetail } from '@/api/healthManaWorkbench/index'
import { debounce, throttle } from '@/utils/tools'
import AiDetail from './AiDetail.vue'

const manaPlanFormRef = ref()
const props = defineProps<{
  isPushed: boolean
  empi: string
  diseaseType: string
  serviceState: string
}>()
// const questionAnswerRef = ref()
const weekDay = reactive<any>(['一', '二', '三', '四', '五', '六', '七'])
const weekLabel = reactive<any>(['周一', '周二', '周三', '周四', '周五', '周六', '周日'])
const sportTypeData = reactive([
  { label: '有氧', value: '1' },
  { label: '抗阻', value: '2' },
  { label: '休息日', value: '3' }
])

const AITaskStatus = ref<any>()
const aiCodeLabel = ref<string>('')
const AITaskData = ref()

const formatter = (value: any) => {
  return `${value}`.replace(/[^0-9]/g, '') // 仅保留数字
}

const filterOption = (input: string, option: any) => {
  return option.value.toUpperCase().indexOf(input.toUpperCase()) >= 0
}

const parser = (value: any) => {
  if (value) {
    return parseInt(value.replace(/[^\d]/g, ''), 10) // 将输入解析为整数
  } else {
    return ''
  }
}

const sportDictData = ref()
const userId = ref()
const templateDataList = ref()

const aerobicData = ref([]) // 有氧运动数据
const addSportModalData = ref([])

const weekData = reactive([
  {
    day: 1,
    warmupSports: [], // 热身
    // 有氧
    aerobicSport: {
      sportId: undefined,
      sportName: undefined,
      total: undefined
    },
    stretchSports: [], // 拉伸
    resistanceSports: [], // 抗阻
    sportType: '1',
    groupNum: undefined
  },
  {
    day: 2,
    warmupSports: [], // 热身
    // 有氧
    aerobicSport: {
      sportId: undefined,
      sportName: undefined,
      total: undefined
    },
    stretchSports: [], // 拉伸
    resistanceSports: [], // 抗阻
    sportType: '1',
    groupNum: undefined
  },
  {
    day: 3,
    warmupSports: [], // 热身
    // 有氧
    aerobicSport: {
      sportId: undefined,
      sportName: undefined,
      total: undefined
    },
    stretchSports: [], // 拉伸
    resistanceSports: [], // 抗阻
    sportType: '1',
    groupNum: undefined
  },
  {
    day: 4,
    warmupSports: [], // 热身
    // 有氧
    aerobicSport: {
      label: undefined,
      time: undefined
    },
    stretchSports: [], // 拉伸
    resistanceSports: [], // 抗阻
    sportType: '1',
    groupNum: undefined
  },
  {
    day: 5,
    warmupSports: [], // 热身
    // 有氧
    aerobicSport: {
      sportId: undefined,
      sportName: undefined,
      total: undefined
    },
    stretchSports: [], // 拉伸
    resistanceSports: [], // 抗阻
    sportType: '1',
    groupNum: undefined
  },
  {
    day: 6,
    warmupSports: [], // 热身
    // 有氧
    aerobicSport: {
      sportId: undefined,
      sportName: undefined,
      total: undefined
    },
    stretchSports: [], // 拉伸
    resistanceSports: [], // 抗阻
    sportType: '1',
    groupNum: undefined
  },
  {
    day: 7,
    warmupSports: [], // 热身
    // 有氧
    aerobicSport: {
      sportId: undefined,
      sportName: undefined,
      total: undefined
    },
    stretchSports: [], // 拉伸
    resistanceSports: [], // 抗阻
    sportType: '1',
    groupNum: undefined
  }
])

// 模板
const individualTemplateList = ref()
const individualOpen = ref<boolean>(false)
const individualName = ref<string>('')
const individualFormData = reactive({
  templateName: '',
  templateType: '',
  content: '',
  data: {}
})

const emit = defineEmits(['update:sportData'])
const sportWeekIndex = ref(0)
const defineModelData = defineModel<any>('sportData', { default: () => [] })
const updatedData = computed({
  get() {
    return defineModelData.value
  },
  set(val) {
    defineModelData.value = val
  }
})

onMounted(async () => {
  aerobicData.value = []
  addSportModalData.value = []
  sportDictData.value = store.userApp.sportDictList.map((vo: any) => {
    return {
      ...vo,
      label: vo.sportName,
      value: vo.sportName
    }
  })

  aerobicData.value = sportDictData.value.filter((item) => {
    return item.isAerobic
  })
  userId.value = store.userApp.userInfo.id

  templateDataList.value = await getTemplateList(null, null)

  setTimeout(() => {
    // updatedData.value = [...props.sportData]
    // if (updatedData.value) {
    //   updatedData.value.forEach((item: any) => {
    //     if (item.templateAffiliation == 'AI生成') {
    //       item.AIContent = JSON.parse(JSON.stringify(item.content))
    //       aiGenerateStatus(item)
    //     }
    //   })
    // }
    if (
      updatedData.value &&
      updatedData.value[0] &&
      updatedData.value[0].templateAffiliation == 'AI生成'
    ) {
      getAiTask() // ai周期任务
    } else {
      updatedData.value.forEach((v: any) => {
        v.activeKey = 0
      })
    }
  }, 300)
})

// 查询Ai生成的状态
const aiGenerateStatus = (data) => {
  return getAiRecommendScheme({
    empi: props.empi,
    code: 'SPORT',
    diseaseType: props.diseaseType
  }).then((res: any) => {
    if (res.data) {
      data.aiStatus = res.data.status
      const content = res.data.content ? JSON.parse(res.data.content) : ''
      if (content) {
        // data.content = content
      } else {
        data.content = {
          week: weekData
        }
      }
      data.AITaskData = content
      data.AIContent = content
    } else {
      AITaskStatus.value = -1
    }

    transformAISattus(data)
  })
}

// // 查看问卷信息
// const getDietQuestion = () => {
//   questionAnswer({ questionnaireRecordId: props.recordId, empi: props.empi }).then((res: any) => {
//     questionAnswerRef.value.init(res.data)
//   })
// }

// watchEffect(() => {
//   if (props.sportData && props.sportData.length > 0) {
//     updatedData.value = [...props.sportData]
//   }
// })

// const removePlanItem = (index: any) => {
//   updatedData.value.splice(index, 1) // 删除指定项
//   updatedData.value = [...updatedData.value]
//   emit('update:sportData', updatedData.value)
// }

// 有氧运动切换
const aerobicChange = (child, index, e) => {
  const data: any = aerobicData.value.find((vo: any) => vo.label === e)
  child.aerobicSport.sportId = data.sportId
}

// 模板切换
const changeTemplate = (data, type) => {
  console.log('切换tab', data, type)
  if (props.isPushed) {
    return
  } else {
    data.activeKey = 0
    if (data.templateAffiliation == type) {
      //
    } else {
      data.templateAffiliation = type
      if (type == 'AI生成') {
        getAiTask()
        // aiGenerateStatus(data)
        // if (data.AIContent) {
        //   data.content = JSON.parse(JSON.stringify(data.AIContent))
        // } else {
        //   data.content.week = weekData
        // }
      } else {
        data.templateList = templateDataList.value.filter((tem) => {
          if (type == '个人模板') {
            return (
              tem.templateType == data.templateType &&
              tem.templateAffiliation == type &&
              tem.creator == userId.value
            )
          } else {
            return tem.templateType == data.templateType && tem.templateAffiliation == type
          }
        })
        if (type == '个人模板') {
          if (data.personTempId) {
            data.templateList.findIndex((ele) => {
              return ele.id == data.personTempId
            }) === -1 &&
              data.templateList.push({
                templateId: data.personTempId,
                templateName: data.personTempName,
                content: data.personTempContent,
                templateType: '运动方案',
                templateAffiliation: '个人模板',
                creator: userId.value,
                label: data.templateName,
                value: data.personTempId,
                id: data.personTempId
              })
          }
        }

        if (data.oldTemplateAffiliation != type) {
          data.templateId = data.templateList.length > 0 ? data.templateList[0].id : undefined
        } else {
          data.templateId = data.oldTemeplateId
        }

        const temData: any = data.templateList.find((tem) => {
          return tem.id == data.templateId
        })
        data.content = temData ? temData.content : ''

        if (data.content) {
          const contentDiet = JSON.parse(data.content)

          data.content = contentDiet
        } else {
          data.content = {
            week: weekData
          }
        }

        data.cycleStart = null
        updatedData.value = [data]
      }
    }
  }
}

// 调用ai生成
const aiGenerateApi = (data: any) => {
  getAiRecommendSchemeDetail({
    empi: props.empi,
    code: 'SPORT',
    diseaseType: props.diseaseType
  }).then(() => {
    data.aiStatus = 20

    transformAISattus(data)
  })
}

// 重新生成ai方案
const regenerate = (data: any) => {
  if ([30, 40].includes(data.aiStatus) || !data.aiStatus) {
    aiGenerateApi(data)
  }
}

const transformAISattus = (data: any) => {
  switch (data.aiStatus) {
    case 10:
      data.aiCodeLabel = '可通过AI大模型为用户生成运动方案'
      return ''
    case 20:
      data.aiCodeLabel = '正在根据用户健康数据，生成AI运动方案...'
      return ''
    case 30:
      data.aiCodeLabel = 'AI生成失败，请重新生成'
      return '重新生成'
    case 40:
      data.aiCodeLabel =
        data.pushStatus == '待推送'
          ? '以下方案由AI依据用户健康数据和运动反馈生成，请审核确认'
          : '以下方案由AI依据用户健康数据生成，请审核确认'
      return ''
    default:
      data.aiCodeLabel = '可通过AI大模型为用户生成运动方案'
      return 'AI生成'
  }
}

// 查看AI生成的周期任务
const getAiTask = () => {
  const params = {
    empi: props.empi,
    planType: 'SPORT'
  }

  getAiCycleTask(params).then(async (res: any) => {
    const aitaskList: any = []
    if (res.data && res.data.length > 0) {
      res.data.forEach((item: any, index: number) => {
        const parsed = item.modelContent ? JSON.parse(item.modelContent) : {}
        const vo = {
          id: item.id,
          aiStatus: 40,
          AIContent: parsed,
          content: parsed,
          AITaskData: parsed,
          templateAffiliation: 'AI生成',
          templateType: '运动方案',
          cycleStart: dayjs(item.cycleStart).format('YYYY-MM-DD'),
          cycleEnd: dayjs(item.cycleEnd).format('YYYY-MM-DD'),
          pushStatus: item.pushStatus,
          aiCodeLabel:
            item.pushStatus == '待推送'
              ? '以下方案由AI依据用户健康数据和运动反馈生成，请审核确认'
              : '',
          onShowTask: index ? false : true,
          activeKey: 0,
          oldTemeplateId: updatedData.value[0].oldTemeplateId,
          oldTemplateAffiliation: updatedData.value[0].oldTemplateAffiliation
        }
        aitaskList.push(vo)
      })

      const findIndex = aitaskList.findIndex((item) => item.pushStatus == '待推送')
      if (findIndex > -1) {
        await aiGenerateStatus(aitaskList[findIndex])
        updatedData.value = [...aitaskList]
        console.log(updatedData.value)
      } else {
        updatedData.value = [...aitaskList]
      }
    }

    if (aitaskList.length == 0 && updatedData.value.length == 0) {
      const mock = {
        templateAffiliation: 'AI生成',
        templateId: undefined,
        templateType: '运动方案',
        cycleStart: null,
        aiCodeLabel: '',
        onShowTask: true,
        pushStatus: null,
        content: {
          week: weekData
        },
        activeKey: 0,
        aiStatus: -1
      }

      aitaskList.push(mock)
      await aiGenerateStatus(aitaskList[0])
      updatedData.value = [...updatedData.value, ...aitaskList]
    } else if (updatedData.value.length == 1) {
      if (updatedData.value[0].oldTemplateAffiliation != 'AI生成') {
        const mock = {
          templateAffiliation: 'AI生成',
          templateId: undefined,
          templateType: '运动方案',
          cycleStart: null,
          aiCodeLabel: '',
          onShowTask: true,
          pushStatus: null,
          content: {
            week: weekData
          },
          activeKey: 0,
          aiStatus: -1,
          oldTemeplateId: updatedData.value[0].oldTemeplateId,
          oldTemplateAffiliation: updatedData.value[0].oldTemplateAffiliation
        }

        if (aitaskList.length > 0) {
          console.log(aitaskList[0])
          if (dayjs(aitaskList[0].cycleEnd).isBefore(dayjs())) {
            aitaskList.unshift(mock)
          }
        } else {
          aitaskList.unshift(mock)
        }
        await aiGenerateStatus(aitaskList[0])
        updatedData.value = [...aitaskList]
      } else {
        await aiGenerateStatus(updatedData.value[0])
        updatedData.value = [...updatedData.value]
      }
    } else {
      if (JSON.stringify(aitaskList[0].content) === '{}') {
        await aiGenerateStatus(aitaskList[0])
        updatedData.value = [...aitaskList]
      }
    }
  })
}

// 查看ai生成的方案
const aiDetailRef = ref()
const aiDetailIndex = ref()
const showAiDetail = (data: any, index: any) => {
  const res = JSON.parse(JSON.stringify(data.AITaskData))
  aiDetailIndex.value = index
  aiDetailRef.value.init(res, 'sports')
}

// 使用ai方案
const setAiPlan = (data: any) => {
  updatedData.value[aiDetailIndex.value].content = data
}

const addPlanItem = () => {
  updatedData.value.push({
    templateAffiliation: '公共模板',
    templateId: undefined,
    templateType: '运动方案',
    templateList: templateDataList.value.filter((tem) => {
      return tem.templateType == '运动方案' && tem.templateAffiliation == '公共模板'
    }),
    content: {
      week: weekData
    }
  })

  // emit('update:sportData', updatedData.value)
}

// 选择模板切换
const templateChange = (data, e, index) => {
  data.activeKey = 0
  // 根据选择的模板更新内容
  const selectedTemplate = data.templateList.find((tem) => tem.id == e)
  data.content = selectedTemplate ? JSON.parse(selectedTemplate.content) : ''
  data.templateId = e
  updatedData.value[index] = { ...data }

  emit('update:sportData', updatedData.value)
}

// 运动类型切换
const changesportType = (data: any, index: any, e: any, childIndex: any) => {
  if (!data.resistanceSports) {
    data.resistanceSports = []
  }

  if (!data.stretchSports) {
    data.stretchSports = []
  }

  if (!data.warmupSports) {
    data.warmupSports = []
  }

  if (!data.groupNum) {
    data.groupNum = undefined
  }

  if (!data.aerobicSport) {
    data.aerobicSport = {
      sportId: undefined,
      sportName: undefined,
      total: undefined
    }
  }
  // }
}

// 展示个人模板保存
const showIndividual = (data) => {
  // 模板类型判断
  try {
    data.content.week.forEach((vo) => {
      if (vo.sportType == '1') {
        if (
          !vo.aerobicSport.sportName ||
          !vo.aerobicSport.total ||
          vo.stretchSports.length == 0 ||
          vo.warmupSports.length === 0
        ) {
          message.error(`运动方案请填写完整`)
          throw Error()
        }
      }

      if (vo.sportType == '2') {
        if (
          vo.groupNum == 0 ||
          vo.resistanceSports.length == 0 ||
          vo.stretchSports.length == 0 ||
          vo.warmupSports.length === 0
        ) {
          message.error(`运动方案请填写完整`)
          throw Error()
        }
      }
    })
  } catch {
    return
  }

  individualTemplateList.value = []
  nextTick(() => {
    individualOpen.value = true
    if (individualForm.value) {
      individualForm.value.resetFields()
    }
    individualFormData.templateName = ''
    individualName.value = '运动方案个人模板库'
    individualFormData.templateType = '运动方案'
    individualFormData.content = data.content
    individualFormData.data = data // 需要保存的模板数据
    const listData = templateDataList.value.filter((tem) => {
      return (
        tem.templateType == '运动方案' &&
        tem.templateAffiliation == '个人模板' &&
        tem.creator == userId.value
      )
    })
    listData.forEach((item) => {
      individualTemplateList.value.push({
        value: item.templateName,
        label: item.templateName
      })
    })
  })
}

// 个人模板保存
const individualForm = ref()
const saveIndividual = () => {
  individualForm.value.validate().then(() => {
    // 对应模板类型的所有个人模板数据
    const templateData = templateDataList.value.filter((tem) => {
      return (
        tem.templateType == individualFormData.templateType &&
        tem.templateAffiliation == '个人模板' &&
        tem.creator == userId.value
      )
    })
    const temContent = individualFormData.data.content
    individualFormData.templateName = individualFormData.templateName.replace(/\s+/g, '')
    const data = {
      id: null,
      templateName: individualFormData.templateName,
      templateType: individualFormData.templateType,
      content: JSON.stringify(temContent),
      templateAffiliation: '个人模板',
      platformId: store.userStore.platformId
    }
    if (templateData.length > 0) {
      const someData = templateData.filter((item) => {
        return item.templateName === individualFormData.templateName
      })
      data.id = someData.length > 0 ? someData[0].id : null
    }
    TemplateAddOrUpdate(data).then(async (res) => {
      individualOpen.value = false
      templateDataList.value = await getTemplateList(null, null)
      updatedData.value.map((item) => {
        item.templateList = templateDataList.value.filter((tem) => {
          return (
            tem.templateType == individualFormData.templateType &&
            tem.templateAffiliation == '个人模板' &&
            tem.creator == userId.value
          )
        })

        item.templateList.findIndex((ele) => {
          return ele.templateId == item.personTempId
        }) === -1 &&
          item.templateList.push({
            templateId: item.personTempId,
            templateName: item.personTempName,
            content: item.personTempContent,
            templateType: '运动方案',
            templateAffiliation: '个人模板',
            creator: userId.value,
            label: item.templateName,
            value: item.personTempId,
            id: item.personTempId
          })
      })
      message.success('保存成功')
      emit('update:sportData', updatedData.value)
    })
  })
}
// 根据方案类型 模板类型获取响应的列表
const getTemplateList = async (templateType, templateAffiliation) => {
  let data: any = []
  const res = await getTemplateDetailList({
    templateType: templateType,
    templateAffiliation: templateAffiliation,
    platformId: store.userStore.platformId
  })

  res.data.map((item: any) => {
    item.label = item.templateName
    item.value = item.id
  })
  data = res.data
  return data
}

//
const sportFormRef = ref<any>()
const sportType = ref<any>('')
const sportTimeName = ref<any>('')
const sportFormDisable = ref<boolean>(false)
const sportTaskIndex = ref<any>()
const sportActionIndex = ref<any>()
const timeStep = ref<any>(4)
const sportOpen = ref(false)
const sportForm = reactive({
  sport: '',
  time: '',
  sportId: undefined
})
const showSport = (type: any, handleType: any, index: any, sportIndex?: any) => {
  sportType.value = type
  sportFormDisable.value = handleType === 'edit' ? true : false

  sportTaskIndex.value = index

  if (!props.isPushed && !getDayDisabled(updatedData.value[index])) {
    switch (sportType.value) {
      case 'resistanceSports':
        timeStep.value = 4
        sportTimeName.value = '运动次数'
        addSportModalData.value = sportDictData.value.filter((item) => {
          return item.isResistance
        })
        break
      case 'warmupSports':
        timeStep.value = 4
        sportTimeName.value = '运动次数'
        addSportModalData.value = sportDictData.value.filter((item) => {
          return item.isWarmup
        })
        break
      case 'stretchSports':
        timeStep.value = 10
        sportTimeName.value = '运动时间(秒)'
        addSportModalData.value = sportDictData.value.filter((item) => {
          return item.isStretch
        })
        break
      default:
        timeStep.value = 4
        sportTimeName.value = '运动次数'
        break
    }

    nextTick(() => {
      sportOpen.value = true
      if (sportFormRef.value) {
        sportFormRef.value.clearValidate()
      }
      const data = {
        sport: '',
        time: '',
        sportId: ''
      }
      if (sportIndex != undefined || sportIndex != null) {
        sportActionIndex.value = sportIndex
        data.sport =
          updatedData.value[index].content.week[updatedData.value[index].activeKey][type][
            sportIndex
          ].sportName
        data.time =
          updatedData.value[index].content.week[updatedData.value[index].activeKey][type][
            sportIndex
          ].total
        data.sportId =
          updatedData.value[index].content.week[updatedData.value[index].activeKey][type][
            sportIndex
          ].sportId
      }
      Object.assign(sportForm, data)
    })
  }
}

const sportTimeChange = debounce((value: any) => {
  if (typeof value === 'number') {
    const numValue = Number(value)
    if (!isNaN(numValue)) {
      const adjusted =
        numValue % timeStep.value !== 0
          ? Math.round(numValue / timeStep.value) * timeStep.value
          : numValue

      if (adjusted) {
        sportForm.time = adjusted + ''
      } else {
        sportForm.time = timeStep.value + ''
      }
    }
  }
}, 600)

// 运动方式切换
const sportModalChange = (e: any) => {
  const data: any = addSportModalData.value.find((vo) => vo.label === e)
  sportForm.sportId = data.sportId
}

// 删除
const delSport = (type: any, index: any, sportIndex: any) => {
  updatedData.value[index].content.week[updatedData.value[index].activeKey][type].splice(
    sportIndex,
    1
  )
}

const sportConfirm = () => {
  sportFormRef.value
    .validate()
    .then(() => {
      const data: any =
        updatedData.value[sportTaskIndex.value].content.week[
          updatedData.value[sportTaskIndex.value].activeKey
        ][sportType.value]

      if (sportFormDisable.value) {
        data[sportActionIndex.value] = {
          sportName: sportForm.sport,
          total: sportForm.time,
          sportId: sportForm.sportId
        }
      } else {
        data.push({
          sportName: sportForm.sport,
          total: sportForm.time,
          sportId: sportForm.sportId
        })
      }

      sportOpen.value = false
    })
    .catch((e: any) => {
      console.log(e)
      //
    })
}

// 时间段中的时间与当前时间对比
const getDayDisabled = (data: any) => {
  if (data.templateAffiliation == 'AI生成') {
    if (dayjs(data.cycleStart).add(data.activeKey, 'day').isSame(dayjs(), 'day')) {
      if (props.isPushed) {
        return true
      } else {
        return false
      }
    } else {
      if (props.isPushed) {
        return true
      } else {
        return dayjs(data.cycleStart).add(data.activeKey, 'day').isBefore(dayjs())
      }
    }
  } else {
    return props.isPushed
  }
}

const tabsChange = (e: any, data: any) => {
  data.activeKey = e
}
</script>
<style lang="less" scoped>
.mana-plan-item-info {
  padding: 16px 0;
  padding-left: 16px;
  border: 1px solid #e5e6eb;
}

.mana-plan-form .ant-form-item {
  padding-left: 24px;
  margin-bottom: 12px;
}

.mana-plan-form .sprot-form {
  .ant-form-item {
    margin-bottom: 18px;
  }
}

.template-col {
  padding: 6px 20px;
  cursor: pointer;
  border: 1px solid #e5e5e5;
  border-radius: 2px;
}

.template-col.template-col-active {
  color: #165dff;
  background: #e8f3ff;
  border: 1px solid #165dff;
  border-radius: 2px 0 0 2px;
}

.sport-group {
  min-height: 42px;
  padding: 0 4px;
  border: 1px solid #d9d9d9;
}

.sport-name {
  display: inline-block;
  padding: 5px 8px;
  margin: 4px;
  color: #1d2129;
  background: #f2f3f5;
  border-radius: 2px;
}

.sport-del-icon {
  margin-left: 4px;
  font-size: 12px;
  color: #4e5969;
  cursor: pointer;
}

.sport-time {
  color: #165dff;
  cursor: pointer;
}

.sport-btn {
  display: inline-block;
  padding: 5px 8px;
  margin: 4px;
  color: #165dff;
  cursor: pointer;
  background: #e8f3ff;
}

.ai-state-icon {
  width: 20px;
  height: 20px;
  margin-right: 8px;
}

.mana-plan-time {
  display: flex;
  align-items: center;
  height: 40px;
  padding: 9px 12px;
  cursor: pointer;
  border: 1px solid #e5e6eb;
  border-radius: 4px 4px 0 0;

  .time-label {
    margin: 0 6px;
  }
}

.mana-plan-time:hover {
  color: #69b1ff;
}

.mana-plan-task {
  padding: 0;
  border-width: 0;
}

.mana-plan-ai {
  padding: 16px;
  border: 1px solid #e5e6eb;
  border-top-width: 0;
}
</style>
